﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Srs.Sample.UI.CustomerService;
using System.ComponentModel;

namespace Srs.Sample.UI.WebParts
{
    [Guid("76C3738B-A7AB-423b-A5FA-36679FC1680A")]
    public class SrsAjaxUpdateWebPart : WebPart
    {
        TextBox _txtCustomerID;
        TextBox _txtCustomerName;
        bool _error = false;
        UpdatePanel updatePanel;
        Label _statusMessage;

        UpdateProgress _updProgress;

        public SrsAjaxUpdateWebPart()
        {
            ViewState[ViewStateKey] = "";
        }

        //TODO: Globalize / externalize strings in resources
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {
                    base.CreateChildControls();

                    //UpdatePanel stuff
                    this.EnsurePanelFix();
                    updatePanel = new UpdatePanel();
                    updatePanel.ID = "updatePanel";
                    updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
                    updatePanel.ChildrenAsTriggers = true;

                    //Retrieval section of view
                    Label lblCustomerId = new Label();
                    lblCustomerId.ID = "customerIdLabel";
                    lblCustomerId.Text = "Customer ID";

                    _txtCustomerID = new TextBox();
                    _txtCustomerID.ID = "customerIdValue";

                    Button btnGetCustomer = new Button();
                    btnGetCustomer.ID = "getCustomer";
                    btnGetCustomer.Text = "Get Customer";
                    btnGetCustomer.Click += new EventHandler(btnGetCustomer_Click);

                    RegularExpressionValidator idValid = new RegularExpressionValidator();
                    idValid.ID = "vldCustomerId";
                    idValid.ControlToValidate = "customerIdValue";
                    idValid.ErrorMessage = "need to supply a custiomer id";
                    idValid.ValidationExpression = @"^\d+$";
                    idValid.EnableClientScript = false;

                    RequiredFieldValidator idSupplied = new RequiredFieldValidator();
                    idSupplied.ID = "vldCustomerIdReq";
                    idSupplied.ControlToValidate = "customerIdValue";
                    idSupplied.ErrorMessage = "Please supply and ID";
                    idSupplied.EnableClientScript = false;

                    //Update section of view
                    Label lblCustomerName = new Label();
                    lblCustomerName.ID = "customerNameLabel";
                    lblCustomerName.Text = "Customer Name";

                    _txtCustomerName = new TextBox();
                    _txtCustomerName.ID = "customerName";

                    Button btnUpdateCustomer = new Button();
                    btnUpdateCustomer.ID = "updateCustomer";
                    btnUpdateCustomer.Text = "Save Customer";
                    btnUpdateCustomer.Click += new EventHandler(btnUpdateCustomer_Click);

                    _statusMessage = new Label();
                    _statusMessage.ID = "statusMessage";
                    _statusMessage.Text = "";

                    //Add relevant controls to the update panel collection - 1st step
                    //Retrieval Section
                    updatePanel.ContentTemplateContainer.Controls.Add(lblCustomerId);
                    updatePanel.ContentTemplateContainer.Controls.Add(_txtCustomerID);
                    updatePanel.AddLineBreak();
                    updatePanel.ContentTemplateContainer.Controls.Add(idValid);
                    updatePanel.ContentTemplateContainer.Controls.Add(idSupplied);
                    updatePanel.AddLineBreak();
                    updatePanel.ContentTemplateContainer.Controls.Add(btnGetCustomer);
                    updatePanel.AddLineBreak();

                    //Update section
                    updatePanel.ContentTemplateContainer.Controls.Add(lblCustomerName);
                    updatePanel.ContentTemplateContainer.Controls.Add(_txtCustomerName);
                    updatePanel.AddLineBreak();
                    updatePanel.ContentTemplateContainer.Controls.Add(btnUpdateCustomer);

                    updatePanel.AddLineBreak();
                    updatePanel.ContentTemplateContainer.Controls.Add(_statusMessage);


                    //Get Script Manager for the control and page
                    this.Controls.Add(this.GetScriptManager());

                    //Add Update panel to the control collection 2nd step
                    this.Controls.Add(updatePanel);
                    
                }
                catch (Exception ex)
                {
                    updatePanel.HandleException(ex, ref _error, false);

                }

            }

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureChildControls();

            _updProgress = new UpdateProgress();
            _updProgress.AssociatedUpdatePanelID = "updatePanel";
            _updProgress.ProgressTemplate = new ProgressTemplate();

            this.Controls.Add(_updProgress);
        }


     
        void btnUpdateCustomer_Click(object sender, EventArgs e)
        {
            CustomerServiceClient svc = new CustomerServiceClient();
            try
            {
                Customer customer = new Customer();
                customer.ID = int.Parse(_txtCustomerID.Text);
                customer.Name = _txtCustomerName.Text;
                customer.Version = ViewState[ViewStateKey].ToString().StringToTimestamp();
                int custId = svc.SaveCustomer(customer);

                customer = svc.GetCustomer(custId);

                //Testing
                System.Threading.Thread.Sleep(2000);

                SetCustomerDisplay(customer);
                _statusMessage.Text = "updated...";


            }
            catch (Exception ex)
            {
                updatePanel.HandleException(ex, ref _error, false);

            }
            finally
            {
                svc.Dispose();
            }
        }

        void btnGetCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                CustomerService.CustomerServiceClient svc = new CustomerServiceClient();
                Customer customer = svc.GetCustomer(int.Parse(_txtCustomerID.Text));


                //Testing
                System.Threading.Thread.Sleep(2000);


                SetCustomerDisplay(customer);

            }
            catch (Exception ex)
            {
                updatePanel.HandleException(ex, ref _error, false);

            }

        }


        void SetCustomerDisplay(Customer customer)
        {
            _txtCustomerName.Text = customer.Name;
            ViewState[ViewStateKey] = customer.Version.TimestampToString();
            _statusMessage.Text = "retrieved";
        }

        string ViewStateKey
        {
            get
            {
                return "customerRecordVersion" + this.UniqueID;
            }
        }        
    }
}
